package cn.wildfire.chat.kit.group.manage;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.lqr.optionitemview.OptionItemView;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.utils.TakeoverInterfaceHub;
import cn.wildfire.chat.app.main.GroupVIPSetActivity;
import cn.wildfire.chat.app.main.TakeOverGroupOwerActivity;
import cn.wildfire.chat.app.main.TakeoverGroupListener;
import cn.wildfire.chat.kit.group.GroupViewModel;
import cn.wildfirechat.model.GroupInfo;
import cn.wildfirechat.model.GroupMember;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;
import cn.wildfirechat.remote.GeneralCallback;

public class GroupManageFragment extends Fragment {

    @BindView(R2.id.vipOptionItemView)
    OptionItemView vipOptionItemView;
    @BindView(R2.id.transferOptionItemView)
    OptionItemView transferOptionItemView;
    private static GroupInfo groupInfo;
    @BindView(R2.id.joinOptionItemView)
    OptionItemView joinOptionItemView;
    @BindView(R2.id.searchOptionItemView)
    OptionItemView searchOptionItemView;
    @BindView(R2.id.permissionOptionItemView)
    OptionItemView permissionOptionItemView;
    @BindView(R2.id.managerOptionItemView)
    OptionItemView managerOptionItemView;
    @BindView(R2.id.muteOptionItemView)
    OptionItemView muteOptionItemView;

    public static GroupManageFragment newInstance(GroupInfo groupInfo) {
        Bundle args = new Bundle();
        args.putParcelable("groupInfo", groupInfo);
        GroupManageFragment fragment = new GroupManageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * modify by HEKE , 2019/8/23 19:15
     * TODO 判断进入的是否是普通管理员
     */
    private boolean isNormalManager;
    private boolean isFromGroupSet;

    public void setNormalManager(boolean isNormalManager) {
        this.isNormalManager = isNormalManager;
        this.isFromGroupSet = true;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        groupInfo = getArguments().getParcelable("groupInfo");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.group_manage_fragment, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        String[] types = getResources().getStringArray(R.array.group_join_type);
        joinOptionItemView.setRightText(types[groupInfo.joinType]);

        /**
         * modify by HEKE , 2019/8/23 19:18
         * TODO  设置成员权限、转让群主功能显示或隐藏
         */
        if (isFromGroupSet) {
            if (isNormalManager) {
                transferOptionItemView.setVisibility(View.GONE);
                managerOptionItemView.setVisibility(View.GONE);
                muteOptionItemView.setVisibility(View.VISIBLE);
                permissionOptionItemView.setVisibility(View.VISIBLE);
                //vipOptionItemView.setVisibility(View.GONE);
            } else {
                permissionOptionItemView.setVisibility(View.VISIBLE);
                transferOptionItemView.setVisibility(View.VISIBLE);
                managerOptionItemView.setVisibility(View.VISIBLE);
                muteOptionItemView.setVisibility(View.VISIBLE);
                //vipOptionItemView.setVisibility(View.VISIBLE);
            }
        }
    }

    @OnClick(R2.id.managerOptionItemView)
    void showGroupManagerSetting() {
        Intent intent = new Intent(getActivity(), GroupManagerListActivity.class);
        intent.putExtra("groupInfo", groupInfo);
        startActivity(intent);
    }

    @OnClick(R2.id.muteOptionItemView)
    void showGroupMuteSetting() {
        Intent intent = new Intent(getActivity(), GroupMuteActivity.class);
        intent.putExtra("groupInfo", groupInfo);
        startActivity(intent);
    }

    @OnClick(R2.id.permissionOptionItemView)
    void showMemberPermissionSetting() {
        Intent intent = new Intent(getActivity(), GroupMemberPermissionActivity.class);
        intent.putExtra("groupInfo", groupInfo);
        startActivity(intent);
    }

    /**
     * 设置当前群组内容的私下交友属性
     *
     * @param privateChat
     */
    public static void setPrivateChat(int privateChat) {
        groupInfo.privateChat = privateChat;
    }

    @OnClick(R2.id.joinOptionItemView)
    void showJoinTypeSetting() {
        GroupViewModel groupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class);
        new MaterialDialog.Builder(getActivity())
                .items(R.array.group_join_type)
                .itemsCallback((dialog, itemView, position, text) -> {
                    groupViewModel.setGroupJoinType(groupInfo.target, position)
                            .observe(GroupManageFragment.this, booleanOperateResult -> {
                                if (booleanOperateResult.isSuccess()) {
                                    joinOptionItemView.setRightText((String) text);
                                } else {
                                    Toast.makeText(getActivity(), "修改加群方式失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                }).show();
    }

    @OnClick(R2.id.searchOptionItemView)
    void showSearchSetting() {
        new MaterialDialog.Builder(getActivity())
                .items(R.array.group_search_type)
                .itemsCallback((dialog, itemView, position, text) -> {
                    searchOptionItemView.setRightText((String) text);
                })
                .show();
    }


    @OnClick(R2.id.transferOptionItemView)
    public void showTransferSetting() {
        try {
            /**
             * modify by HEKE , 2019/8/23 20:40
             * TODO 转让群主，传递群成员列表信息
             */
            GroupViewModel groupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class);
            List<GroupMember> groupMemberList = groupViewModel.getGroupMembers(groupInfo.target, true);
            if (groupMemberList != null) {
                ArrayList<UserInfo> userInfoArrayList = new ArrayList<>();
                String selfId = ChatManager.Instance().getUserId();
                for (GroupMember groupMember : groupMemberList) {
                    if (!groupMember.memberId.equals(selfId)) {
                        UserInfo userInfo = ChatManager.Instance().getUserInfo(groupMember.memberId, false);
                        userInfoArrayList.add(userInfo);
                    }
                }
                if (userInfoArrayList != null) {
                    TakeoverInterfaceHub.setTakeoverGroupListener(takeoverGroupListener);
                    Intent intent = new Intent(getActivity(), TakeOverGroupOwerActivity.class);
                    intent.putExtra("groupInfo", groupInfo);
                    startActivity(intent);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * modify by HEKE , 2019/8/23 20:57
     * TODO 回调转让群主信息接口
     */
    private TakeoverGroupListener takeoverGroupListener = new TakeoverGroupListener() {
        @Override
        public void callback(UserInfo userInfo) {
            try {
                // TODO 设置新的群主信息
                ChatManager.Instance().transferGroup(groupInfo.target, userInfo.uid, Arrays.asList(0), null, new GeneralCallback() {
                    @Override
                    public void onSuccess() {
                        try {
                            if (TakeoverInterfaceHub.getOnRefreshGroupInfosListener() != null) {
                                TakeoverInterfaceHub.getOnRefreshGroupInfosListener().refreshReq();
                            }
                            getActivity().finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(int errorCode) {
                        Toast.makeText(getActivity(), "转让失败!", Toast.LENGTH_SHORT).show();
                    }
                });
                TakeoverInterfaceHub.releaseTOG();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @OnClick(R2.id.vipOptionItemView)
    public void onViewClicked() {
        Intent intent = new Intent(getActivity(), GroupVIPSetActivity.class);
        intent.putExtra("groupInfo", groupInfo);
        startActivity(intent);
    }

}
